<template>
  <view class="goods">
    <scroll-view class="whf oh" scroll-y>
      <!-- p1em -->
      <view v-if="!!data" class="y">
        <swiper indicator-dots autoplay class="swiper">
          <swiper-item v-for="(i, ii) in data.banner" :key="ii">
            <image :src="i.url" mode="aspectFill" class="fg1 whf" webp show-menu-by-longpress />
          </swiper-item>
        </swiper>
        <view class="goods-padding">
          <view class="title mt04em">
            <text class="is_shiwu" v-if="data.tagOne">「{{ data.tagOne }}」</text>
            {{ data.name }}
          </view>
          <view class="money">
            <view v-if="data._goodsType && data._goodsType.name" class="type"> {{ data._goodsType.name }} </view>
            <text>单价:</text>
            <text class="mac-ico-jiage">{{ data.money / 100 }}</text>
          </view>
          <view class="goods-sold">{{ data.sold ? data.sold : 0 }} 已销售</view>
          <view class="content mt1em">
            <rich-text :nodes="data.des" />
          </view>
        </view>

        <view class="bottom" style="position:relative" />
      </view>
    </scroll-view>
    <!-- goods-padding -->
    <view class="bottom x jc p1em bottom-tabs">
      <view class="bottom-ico">
        <view class="bottom-ico-item" @click="homeClick()">
          <view class="iconfont mac-ico-home"></view>
          <view class="bottom-ico-item-text">首页</view>
        </view>
        <view class="bottom-ico-item" @click="cartClick()">
          <view class="iconfont mac-ico-cart"></view>
          <view class="bottom-ico-item-text">购物车</view>
        </view>
      </view>
      <view class="cart_pay">
        <view class="cart" @click="showpop('car')">加入购物车</view>
        <view class="pay" @click="showpop('pay')">立即支付</view>
      </view>
    </view>
    <view :class="[{ 'popup': true }, { 'popup_active': popupShow }]">
      <view :class="[{ 'popup-mask': true }, { 'popup-mask_active': popupShow }]" @click="popupShow = false" />
      <scroll-view :class="[{ 'popup-content': true }, { 'popup-content_active': popupShow }]" v-if="!!data">
        <view class="popup-item">
          <view class="popup-img">
            <image v-if="data.banner[0] && data.banner[0].url" :src="data.banner[0].url" mode="scaleToFill"
              webp show-menu-by-longpress />
          </view>
          <view class="popup-text">
            <view class="popup-title">
              <text class="is_shiwu" v-if="data.tagOne">「{{ data.tagOne }}」</text>
              {{ data.name }}
            </view>
            <view class="popup-money">￥{{ data.money / 100 }}</view>
            <view class="popup-payment">实付 <text>￥{{ data.money / 100 }}</text></view>
            <view class="popup-nums">
              <view class="popup-nums-minus" @click="numsiminus">-</view>
              <view class="popup-nums-input"><input type="number" @blur="numsblur" v-model="numsi" :minlength="1" />
              </view>
              <view class="popup-nums-add" @click="numsadd">+</view>
            </view>
          </view>
        </view>
        <view class="popup-add" v-if="poptype == 'pay'">
          <view class="mac-ico-location-fill"></view>
          <view class="popup-add-info-box" v-if="addressInfo && addressInfo.id" @click="selectAddress">
            <view class="popup-add-info">
              <view class="popup-add-name">{{ addressInfo.name }}</view>
              <view class="popup-add-phone">{{ addressInfo.phone }}</view>
            </view>
            <view class="popup-add-add">{{ addressInfo.addr }}</view>
          </view>
          <view v-else class="popup-add-select" @click="selectAddress">请选择收货地址</view>
        </view>
        <view class="popup-btn" @click="popupChange"> {{ poptype == 'pay' ? '立即支付' : '加入购物车' }} </view>
        <view style="height: 10px;"></view>
      </scroll-view>
    </view>
    <SelectAddressi v-model:addShow="addShow" ref="addref" @selectAddr="selectAddr" />
  </view>
</template>
<script lang="ts">
import gt from "@/globalTypes";
import { apiUrl } from "@/util/static";
import { defineComponent } from "vue";
import SelectAddressi from "@/components/SelectAddress.vue"


function processSrc(src: string, apiUrl: string) {
  if (!/^https?:\/\//i.test(src)) { // 检查是否已经包含 http 或 https
    return `${apiUrl}/${src}`;
  }
  return src;
}

export default defineComponent({
  name: "goods",
  components: {
    SelectAddressi
  },
  data() {
    return {
      data: undefined as gt.sql.goods | undefined,
      id: "",
      sheight: "auto",
      nums: [] as string[],
      refresh: 0,
      popupShow: false,
      numsi: 1,
      poptype: 'car',
      addList: [] as gt.sql.addr[],
      addressInfo: {} as gt.sql.addr,
      addShow: false,
    };
  },
  onLoad(p) {
    if (p) {
      if (p.id) {
        this.id = p.id;
      } else {
        msg({ title: "请点击商品进入", icon: "error" });
      }
      if (p.gid) {
        uni.setStorageSync("gid", p.gid);
      }
      this.init();
    }
  },
  onShow() {
    if (this.addShow) {
      // @ts-ignore
      this.$refs.addref.getAddd();
    }
  },
  methods: {
    async init() {
      if (this.id) {
        uni.showLoading({ title: "正在加载,请稍后", mask: true });

        const goods = await gd.goods.getById(this.id);
        if (!goods) return msg({ title: "商品不存在", icon: "error" });
        goods.des = goods.des
          .replace(/<img([^>]*)>/g, (_match, p1) => {
            // 解析现有的 style 属性
            let newStyle = 'width: 100%; height: auto; overflow: hidden;';
            if (p1.includes('style="')) {
              const existingStyle = p1.match(/style="([^"]*)"/)[1];
              newStyle = `${existingStyle} ${newStyle}`;
            }

            // 处理 src 属性
            const srcMatch = p1.match(/src="([^"]*)"/);
            const newSrc = srcMatch ? `src="${processSrc(srcMatch[1], apiUrl)}"` : '';

            // 替换原有的 style 和 src 属性
            return `<img ${newSrc} style="${newStyle}"${p1.replace(/style="[^"]*"/, '').replace(/src="[^"]*"/, '')}>`;
          })
          .replace(/<video([^>]*)>/g, (_match, p1) => {
            // 解析现有的 style 属性
            let newStyle = 'width: 100%; height: auto; overflow: hidden;';
            if (p1.includes('style="')) {
              const existingStyle = p1.match(/style="([^"]*)"/)[1];
              newStyle = `${existingStyle} ${newStyle}`;
            }

            // 处理 src 属性
            const srcMatch = p1.match(/src="([^"]*)"/);
            const newSrc = srcMatch ? `src="${processSrc(srcMatch[1], apiUrl)}"` : '';

            // 替换原有的 style 和 src 属性
            return `<video ${newSrc} style="${newStyle}"${p1.replace(/style="[^"]*"/, '').replace(/src="[^"]*"/, '')}>`;
          });

        this.data = goods;
        const r: string[] = [];
        const rmax = (parseInt(await getSetting("goodsmax")) || 100) + 1;
        for (let i = 0; i < rmax; i++) {
          r.push(i as any);
        }
        r[0] = "手动输入数量";
        this.nums = r;
        uni.hideLoading();
        // this.refresh ^= 1;
      }
    },
    setSheight() {
      uni.createSelectorQuery().in(this).select(".swiper").boundingClientRect((r) => {
        if (!r) {
          return setTimeout(() => {
            this.setSheight();
          }, 10);
        }
        if (!Array.isArray(r)) {
          this.sheight = r.width + "px";
        }
      }).exec();
    },
    async getSum(p?: any) {
      let ret: number = p?.detail?.value || 0;
      while (!(ret > 0)) {
        const r = await uni.showModal({
          title: "输入数量",
          editable: true,
          placeholderText: "请输入下单数量",
        });
        if (r.confirm) {
          ret = Math.abs(parseInt(r.content));
        } else {
          return 0;
        }
      }
      return ret;
    },
    async cart() {
      const n = this.numsi;
      if (!(this.nums.length > n && n > 0)) {
        msg({ title: "请重新选择数量", icon: "error" });
        return;
      }

      const c: { goods: string; sum: number; gid: string; }[] = uni.getStorageSync("cart") || [],
        i = c.findIndex(e => e.goods == this.id);
      if (i >= 0) {
        c[i].sum += n;
      } else {
        c.push({ gid: uni.getStorageSync("gid"), goods: this.id, sum: n });
      }
      msg({ title: "添加购物车成功", icon: "success" });
      uni.setStorageSync("cart", c);
    },
    async pay() {
      var _this = this
      const sum = this.numsi;
      if (!sum) { return; }
      const r = await api.request({ gid: uni.getStorageSync("gid"), content: [{ goods: this.id, sum, addr: _this.addressInfo.id }] }, "order/create");
      if (r) {
        uni.requestPayment(r);
      }
    },
    homeClick() {
      uni.switchTab({ url: "/pages/index" });
    },
    cartClick() {
      uni.switchTab({ url: "/pages/cart" });
    },
    popupChange() {
      if (this.poptype == 'car') this.cart()
      if (this.poptype == 'pay') this.pay()
      this.popupShow = false
    },
    numsiminus() {
      this.numsi = Math.max(1, this.numsi - 1);
    },
    numsadd() {
      this.numsi = Math.max(1, this.numsi + 1);
    },
    numsblur(e: any) {
      if (!parseInt(e.detail.value)) this.numsi = 1
    },
    showpop(type: string = 'car') {
      this.popupShow = true
      this.poptype = type
    },
    selectAddress() {
      this.addShow = true
    },
    selectAddr(res: gt.sql.addr) {
      this.addressInfo = res
      this.addShow = false
    }
  },
  onReady() {
    this.setSheight();
  }
});
</script>
<style lang="scss" scoped>
.goods {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #FFFFFF;

  .swiper {
    width: 100%;
    height: v-bind(sheight);
  }

  .goods-padding {
    padding: .8em
  }

  .money {
    display: flex;
    align-items: center;
    color: red;
    font-size: .8em;
    font-weight: 600;
    margin-top: .3em;
    display: flex;

    .type {
      padding: .3em .5em;
      background: #673AB7;
      color: #FFFFFF;
      border-radius: 4px;
      font-size: .7em;
      margin-right: .7em
    }
  }

  .title {
    font-size: 1em;

    .is_shiwu {
      margin-right: .2em;
      font-size: .8em;
      color: #ff9800;
    }
  }

  .bottom {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 3.5em;
    background-color: #fff;

    >.mac-ico-message {
      font-size: 2em;
    }

    >.cart {
      background-color: $uni-color-success;
      color: #fff
    }

    >.pay {
      background-color: $uni-color-error;
      color: #fff
    }
  }

}

.goods-sold {
  font-size: .7em;
  color: #9e9e9e;
  margin: .3em 0;
}

.bottom-tabs {
  display: flex;
  padding: 0 0 0 1em;

  >view {
    height: 100%;
  }
}

.bottom-ico {
  display: flex;
  justify-content: space-around;
  align-items: center;
  width: 30%;

  .iconfont {
    font-size: 1.2em;
    color: #333333;
  }

  &-item {
    text-align: center;

    &-text {
      font-size: .6em;
      color: #35241C;
    }
  }
}

.cart_pay {
  display: flex;
  flex: 1;

  >view {
    width: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: .9em;
    color: #fff;
    height: 100%;
  }

  .cart {
    background-color: #35241C;
  }

  .pay {
    // 背景色渐变色
    background-image: linear-gradient(to top, #DE433A, #E66D69);
  }
}

.popup {
  position: fixed;
  top: 0;
  bottom: -100%;
  left: 0;
  right: 0;
  z-index: -9;
  transition: all .2s;

  &_active {
    bottom: 0;
    z-index: 1;
    transition: all .2s;
  }

  &-mask {
    height: 100vh;
    width: 100%;
    background-color: rgba(0, 0, 0, .5);
  }

  &-content {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    max-height: 80vh;
    height: 0;
    padding: 0;
    background-color: #FFFFFF;
    z-index: 99;
    border-radius: 5rpx 5rpx 0 0;
    box-sizing: border-box;
    transition: height .3s;

    &_active {
      height: 20em;
      padding: 20rpx;
      transition: height .3s;
    }
  }

  &-item {
    display: flex;
  }

  &-img {
    width: 150rpx;
    height: 150rpx;
    border-radius: 10rpx;
    overflow: hidden;

    image {
      width: 100%;
      height: 100%;
    }
  }

  &-title {
    font-size: 1em;

    .is_shiwu {
      margin-right: .2em;
      font-size: .8em;
      color: #ff9800;
    }
  }

  &-money {
    color: red;
    font-size: .8em;
    font-weight: 600;
    margin-top: .3em;
    margin-left: 10rpx;
  }

  &-nums {
    display: flex;
    align-items: center;
    margin: 10rpx 0 0 10rpx;
    background-color: #e4e4e4;
    border-radius: 8rpx;
    padding: 0 10rpx;

    &-minus,
    &-add {
      font-size: 1.5em;
    }

    &-minus {
      font-size: 1.8em;
    }

    &-input {
      margin: 0 20rpx;

      input {
        width: 100rpx;
        text-align: center;
        text-align: center;
      }
    }
  }

  &-payment {
    font-size: 1em;
    margin: 10rpx 0 10rpx 10rpx;
    color: #FF5000;

    text {
      color: 1.5em;
      font-weight: 600;
    }
  }

  &-btn {
    background-color: #FF5000;
    color: #FFFFFF;
    width: 100%;
    text-align: center;
    line-height: 80rpx;
    margin: 1em 0 0 0;
    border-radius: 10rpx;
  }

  &-add {
    display: flex;
    padding: 10rpx 0;

    .mac-ico-location-fill {
      color: #666666;
      font-size: 1.6em;
      color: #ff9800;
    }

    &-info-box {
      margin-left: 10rpx;
    }

    &-info {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }

    &-name {
      margin-right: 10rpx;
      background-color: #ff9800;
      color: #FFFFFF;
      border-radius: .2em;
      padding: 4rpx 10rpx;
      font-size: .8em;
      margin-bottom: .3em;
    }

    // &-phone{ }
    &-select {
      margin-left: 10rpx;
      padding: 4rpx 10rpx;
      background-color: #ff9800;
      color: #FFFFFF;
      border-radius: .2em;
      font-size: 1em;
    }
  }
}
</style>